<template>
  <div class="box">
    <div class="btn">
      <a-button size="large" block @click="toEdit(id)" v-if="role === '1'">添加流程事件</a-button>
    </div>
    <div class="btn1">
      <a-button size="large" block v-if="role === '1'" @click="showModal">修改流程名</a-button>
      <a-modal v-model:visible="visible" title="修改流程名" :confirm-loading="confirmLoading" @ok="handleOk">
        <a-form :model="formState" name="basic" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" autocomplete="off">
          <a-form-item class="editprocesssname" label="流程名" name="username" :rules="[{ required: true, message: '请输入流程名！' }]">
            <a-input v-model:value="formState.process_name" />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
    <a-table :columns="role === '1' ? superColumns : adminColumns" :data-source="data" rowKey="id" :pagination="false">
      <template #status="{ record }">
        <a-select ref="select" v-model:value="record.status" @change="handleChange(record.id, record.status, record)" style="width: 100px">
          <a-select-option :value="0">未发布</a-select-option>
          <a-select-option :value="1">进行中</a-select-option>
          <a-select-option :value="2">已结束</a-select-option>
        </a-select>
      </template>
      <template #action="{ record }">
        <a-space>
          <a @click="goCheckout(record.event_id, record.type)">查看</a>
          <a @click="goEdit(record.id)">修改事件</a>
          <a-popconfirm title="确定要删除该事件?" ok-text="删除" cancel-text="取消" @confirm="onDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>
        </a-space>
      </template>
    </a-table>
    <cheack-detail ref="RefChilde" :infoData="detailData" />
  </div>
</template>
<script lang="ts">
import { defineComponent, Ref, ref, onMounted, reactive, toRaw } from 'vue'
import { message } from 'ant-design-vue'
import 'ant-design-vue/es/message/style/css'
import { get, detele, put } from '../../../utils/request/request'
import CheackDetail from '../../../components/chooseDetail/CheackDetail.vue'
import { useRouter } from 'vue-router'

const adminColumns = [
  { title: '标题', dataIndex: 'title', width: '20%', align: 'center' },
  { title: '事件类型', dataIndex: 'type', width: '20%', align: 'center' },
  { title: '日期', dataIndex: 'date', width: '20%', align: 'center' },
  {
    title: '状态',
    dataIndex: 'status',
    width: '15%',
    align: 'center'
  }
]

const superColumns = [
  { title: '标题', dataIndex: 'title', width: '20%', align: 'center' },
  { title: '事件类型', dataIndex: 'type', width: '20%', align: 'center' },
  { title: '日期', dataIndex: 'date', width: '20%', align: 'center' },
  {
    title: '状态',
    dataIndex: 'status',
    width: '15%',
    align: 'center',
    slots: { customRender: 'status' }
  },
  {
    title: '操作',
    key: 'operation',
    fixed: 'right',
    width: '30%',
    align: 'center',
    slots: { customRender: 'action' }
  }
]

interface DataItem {
  id: number //流程id
  title: string //事件标题
  date: string //事件时间
  type: number | string //事件类型：1.报名 2.面试 3.其他事件
  event_id: number
  number: number
}

interface FormState {
  process_name: string
}

const formState = reactive<FormState>({
  process_name: ''
})

const data: Ref<DataItem[]> = ref([])

// 调用子组件方法，打开 modal
const useCheckoutEffect = () => {
  const RefChilde = ref()
  const openCheckoutModal = () => {
    RefChilde.value.showModal()
  }
  return { RefChilde, openCheckoutModal }
}

// 操作栏的相关逻辑
const useOperationEffect = (token: string) => {
  const chosusername = ref<string>('')
  const chosname = ref<string>('')
  const chosrole = ref<number>()
  const detailData = ref({}) // 详情数据
  const { RefChilde, openCheckoutModal } = useCheckoutEffect()
  // 删除事件
  const onDelete = async (id: number) => {
    const res: any = await detele(`/admin/api/v1/recruitment/process/item/${id}`, {}, token)
    if (res.status_code == 0) {
      data.value = data.value.filter((item) => item.id !== id)
      message.success('删除成功')
    } else {
      message.error('删除失败')
    }
  }
  // 查看详情
  const goCheckout = async (id: number, type: string) => {
    if (type == '报名') {
      const paperRes: any = await get(`/admin/api/v1/paper/${id}`, token)
      if (paperRes.data === null) {
        message.warn('该事件未绑定对应的报名问卷')
      } else {
        openCheckoutModal()
        detailData.value = paperRes.data
      }
    } else if (type == '面试') {
      const interviewRes: any = await get(`/admin/api/v1/recruitment/interview/${id}`, token)
      if (interviewRes.data === null) {
        message.warn('该事件未绑定对应的面试')
      } else {
        openCheckoutModal()
        detailData.value = interviewRes.data
      }
    }
  }
  return {
    detailData,
    RefChilde,
    onDelete,
    goCheckout,
    chosusername,
    chosname,
    chosrole
  }
}

// 表格的数据
const useTableDataEffect = (token: string) => {
  const getData = async (id: number) => {
    const res: any = await get(`/admin/api/v1/recruitment/process/${id}`, token)
    const modifiedData = res.data.items
    modifiedData.forEach((item: any) => {
      if (item.type === 1) {
        item.type = '报名'
      } else if (item.type === 2) {
        item.type = '面试'
      } else {
        item.type = '其他事件'
      }
    })
    data.value = modifiedData
  }
  return { getData }
}

//选择器相关逻辑
const useSelectorEffect = (token: string) => {
  const handleChange = async (id: number, status: number, data: any) => {
    const res: any = await put(
      `/admin/api/v1/recruitment/process/item/${id}`,
      {
        status: status
      },
      token
    )
    console.log(res)
    if (res.status_code === 0) {
      message.success('修改成功')
    } else {
      message.error('修改失败')
      data.status = status
    }
  }
  return { focus, handleChange }
}

export default defineComponent({
  components: {
    CheackDetail
  },
  props: ['id'],
  setup(props) {
    const visible = ref<boolean>(false)
    const confirmLoading = ref<boolean>(false)
    const role = ref<string>(localStorage.getItem('role') as string)
    const token: string = localStorage.getItem('token') as string
    const { detailData, RefChilde, onDelete, goCheckout, chosusername, chosname, chosrole } = useOperationEffect(token)
    const { getData } = useTableDataEffect(token)
    const { handleChange } = useSelectorEffect(token)

    //点击编辑跳转到编辑页面
    const router = useRouter()
    const toEdit = (propsId: number) => {
      router.push({ name: 'processEdit', params: { id: propsId } })
    }

    //点击修改跳转页面
    const goEdit = (propsId: number) => {
      router.push({ name: 'eventEdit', params: { id: propsId } })
    }

    const showModal = async () => {
      const res: any = await get(`/admin/api/v1/recruitment/process/${props.id}`, token)
      console.log(res)
      formState.process_name = res.data.process_name
      visible.value = true
    }

    const handleOk = async () => {
      confirmLoading.value = true
      const res: any = await put(`/admin/api/v1/recruitment/process/${props.id}`, toRaw(formState), token)
      if (res.status_code === 0) {
        message.info('修改成功')
        visible.value = false
        confirmLoading.value = false
      } else {
        message.info('修改失败')
      }
    }

    onMounted(() => {
      getData(props.id)
      console.log(props.id)
    })

    return {
      visible,
      goEdit,
      confirmLoading,
      showModal,
      handleOk,
      data,
      role,
      adminColumns,
      superColumns,
      onDelete,
      goCheckout,
      chosusername,
      chosname,
      chosrole,
      getData,
      detailData,
      RefChilde,
      confirm,
      toEdit,
      handleChange,
      formState
    }
  }
})
</script>

<style lang="less" scoped>
.btn {
  padding-bottom: 15px;
  width: 525px;
  text-align: right;
}
.btn1 {
  padding-bottom: 15px;
  width: 525px;
  text-align: right;
  position: absolute;
  top: -0.1px;
  left: 535px;
}
.box {
  position: relative;
  min-height: 700px;
}
.check-icon {
  font-size: 22px;
  padding-right: 10px;
}

.editprocesssname {
  position: relative;
  left: -75px;
  top: 15px;
}
</style>
